'use strict';

stareal
    .controller("UserSendCodeController", function ($scope, $api, $stateParams, $alert, $document, localStorageService, $state, $interval) {
        $scope.telphone_no = $stateParams.mobile;
        $scope.accessToken = "";
        $scope.password = "";
        $scope.password2 = "";
        $scope.paracont = "";
        $scope.code = "";
        $scope.codeStatus=true;
        $scope.scanStatus=false;
        $scope.H5CorderId=localStorageService.get('H5CorderId');
        if($scope.telphone_no!=undefined&&$scope.telphone_no!=''&&$scope.telphone_no!=null){
            $scope.telshow = $scope.telphone_no.substr(0, 3) + '****' + $scope.telphone_no.substr(7);
        }
        var padLeft=($(window).width()-0.64*parseFloat(document.documentElement.style.fontSize)-300)/2+'px';
        var paddL=0.32*parseFloat(document.documentElement.style.fontSize);
        $("#login_registercontainer").height($(window).height());
        $("#tanCode_container").height($(window).height());
        $(".ipt-box-nick-box").css('padding-left',padLeft);
        $("#login_container").height();
        // $("#agreement_radio").click(function(){
        //     if($(this).hasClass("checked")){
        //         $(this).removeClass("checked");
        //     }else{
        //         $(this).addClass("checked");
        //     }
        // })
        //http://localhost/mobile/app/slidingVerificationCode/listjs
        // $scope.$watch('code',function (newValue, oldValue) {
        //     // console.log($scope.code);
        //     if( $scope.code!=''&&$scope.code!=null){
        //         $scope.isActive =  true;
        //     }else{
        //         $scope.isActive =  false;
        //     }
        // });
        //清除
        $scope.clearNumber=function(){
            $scope.telphone_no = "";
        }
        //查看密码
        $scope.scanNumber=function(){
            if(!$scope.scanStatus){
                $scope.scanStatus=true;
                $("#useSendCodeInput").attr('type','text');
            }else{
                $scope.scanStatus=false;
                $("#useSendCodeInput").attr('type','password');
            }

        }
        $(".ipt-real-nick").on("input", function() {
            //console.log($(this).val());
            var $input = $(".ipt-fake-box input");
            if(!$(this).val()){//无值光标顶置
                $(this).removeClass('active');
                $('.ipt-active-nick').css('left',$input.eq(0).offset().left-parseInt($('.ipt-box-nick').parent().css('padding-left'))-paddL+'px');
            }
            if(/^[0-9]*$/g.test($(this).val())){//有值只能是数字
                //console.log($(this).val());
                var pwd = $(this).val().trim();
                for (var i = 0, len = pwd.length; i < len; i++) {
                    $input.eq(i).val(pwd[i]);
                    $input.eq(i).addClass("active");
                    if($input.eq(i).next().length){//模拟光标，先将图片容器定位，控制left值而已
                        $('.ipt-active-nick').css('left',$input.eq(i+1).offset().left-parseInt($('.ipt-box-nick').parent().css('padding-left'))-paddL+'px');
                    }
                }
                $input.each(function() {//将有值的当前input后的所有input清空
                    var index = $(this).index();
                    if (index >= len) {
                        $(this).val("");
                        $(this).removeClass("active");
                    }
                });
                if (len == 6) {
                    //执行其他操作
                    //console.log('输入完整，执行操作');
                    //console.log($(this).val().trim());
                    var valdata=$(this).val().trim()
                    $scope.$apply(
                        function(){
                            console.log(valdata);
                            $scope.code=valdata;
                        }
                    )

                }
            }else{//清除val中的非数字，返回纯number的value
                var arr=$(this).val().match(/\d/g);
                $(this).val($(this).val().slice(0,$(this).val().lastIndexOf(arr[arr.length-1])+1));
                //console.log($(this).val());
            }
        });
        //前往重新发送验证码
        $scope.reSendCode=function(){
            if($scope.codeSendStatus){
                return;
            }
            if (!$scope.login.validatemobile($scope.telphone_no)){
                return;
            }
            $("#tanCode_container").show();
            var capOption = {callback:cbfn, showHeader:false,themeColor:'e72e62',type:"popup"};
            capDestroy();
            capInit(document.getElementById("TCaptcha"),capOption);
            //回调函数：验证码页面关闭时回调
            function cbfn(retJson) {
                console.log(retJson);
                if (retJson.ret == 0) {
                    // 用户验证成功
                    var ticket= retJson.ticket;
                    // document.getElementById("myform").submit();
                    $("#tanCode_container").hide();
                    $api.post("app/slidingVerificationCode/verify",{ticket:ticket,mobile:$scope.telphone_no},true)
                        .then(function (ret){
                            console.log(ret)
                            if (ret.retCode == "0"){
                                $("#tanCode_container").hide();
                                localStorageService.set('code_token', ret.accessToken);
                                $scope.login.sendCode();
                               // $state.go('main.use_sendCode',{mobile:$scope.telphone_no});
                                // $scope.codeStatus=false;
                            }else{
                                $alert.show("验证失败!");
                            }
                        },function(err){
                            $alert.show(err);
                        });


                }else if(retJson.ret ==2){
                    //用户关闭验证码页面，没有验证
                    $("#tanCode_container").hide();
                }else{
                    $alert.show("验证码已发送!");
                }
            }

        }
        $scope.login = {
            sendCode:function (){
                var second = 60;
                var timerHandler = undefined;
                if (!this.validatemobile($scope.telphone_no)){
                    return;
                }
                // // 验证码  app/slidingVerificationCode/verifySelf
                // $api.get("app/login/code/retrieve", {mobile:$scope.telphone_no, type: "0"})
                //     .then(function (ret) {
                //         if (ret.retCode == "0") {
                //             $alert.show("验证码已发送!");
                //             localStorageService.set('code_token', ret.accessToken);
                //         } else {
                //             $alert.show("验证码发送失败，请稍后重试!");
                //         }
                //     });
                if (timerHandler) {
                    return;
                }
                timerHandler = $interval(function () {
                    if (second <= 0) {
                        $interval.cancel(timerHandler);
                        timerHandler = undefined;
                        second = 60;
                        $scope.paracont = "";
                        $scope.codeSendStatus=false;
                    } else {
                        $scope.codeSendStatus=true;
                        $scope.paracont ='('+ second + "s)";
                        second--;

                    }
                }, 1000, 100)
            },
            login:function (){
                // console.log(localStorageService.get('code_token'))
                if (!this.validatemobile($scope.telphone_no)) {
                    return;
                }
                // if(!$scope.isActive){
                //     return false;
                // }
                if (!localStorageService.get('code_token')) {
                    $alert.show("请先获取验证码！");
                    return false;
                }
                if (!$scope.code) {
                    $alert.show("验证码不能为空");
                    return false;
                }
                if($scope.password==null&&$scope.password==''&&$scope.password==undefined){
                    $alert.show("密码不能为空");
                    return false;
                }
                if($scope.password.length<=6){
                    $alert.show("请设置大于6位数密码")
                    return false;
                }
                if($scope.password.length>=18){
                    $alert.show("请设置小于于18位数密码")
                    return false;
                }
                // if($scope.password!==$scope.password2){
                //     $alert.show("两次输入的密码不一样");
                //     return false;
                // }
                // if(!$('#agreement_radio').hasClass("checked")){
                //     $alert.show("请勾选相关协议!");
                //     return false;
                // }

                var _params = {
                    mobile:$scope.telphone_no,
                    code:$scope.code,
                    password:$scope.password,
                    accessToken: localStorageService.get('code_token')
                };

                $api.post("app/login/user/create", _params)
                    .then(function (ret) {
                        $alert.show("注册成功");
                        if($scope.H5CorderId!=undefined&& $scope.H5CorderId!=null&& $scope.H5CorderId!=''){
                            var ua = navigator.userAgent.toLowerCase();
                            $scope.IP=returnCitySN["cip"];  //app/channel/register
                            $api.post("app/channel/register", {
                                device_msg:ua,
                                ip:$scope.IP,
                                code:$scope.H5CorderId,
                                source:'mobile'
                            },true).then(function (ret){
                                console.log(ret);
                            },function(err){
                                $alert.show(err);
                            });
                        }
                        $state.go('main.login',{good_id:$stateParams.good_id})
                        if(_czc!=undefined&&_czc!=null&&_czc!='') {
                            _czc.push(["_trackEvent", 'h5-注册-注册成功', '注册成功', '查看', 'register']);
                        }
                    }, function (err) {
                        if(err=='用户已存在'){
                            $alert.show(err+'请登录！');
                            $state.go('main.login',{good_id:$stateParams.good_id});
                        }else{
                            $alert.show(err);
                        }
                    });
            },
            validatemobile:function (mobile) {
                if(!mobile){
                    $alert.show("请输入手机号")
                    return false
                }
                if (mobile.toString().length == 0) {
                    $alert.show('请输入手机号码！');
                    return false;
                }
                if (mobile.toString().length != 11) {
                    $alert.show('请输入11位手机号码！');
                    return false;
                }
                var myreg = /^1[3|4|5|6|7|8|9][0-9]{9}$/; //验证规则
                if (!myreg.test(mobile)) {
                    $alert.show('请输入有效的手机号码！');
                    return false;
                }
                return true;
            }
        }
        if($scope.telphone_no!=undefined&&$scope.telphone_no!=''&&$scope.telphone_no!=null
            &&localStorageService.get('code_token')!=undefined&&localStorageService.get('code_token')!=''&&localStorageService.get('code_token')!=null){
            $scope.login.sendCode();
            $scope.codeSendStatus=true;
        }
        $scope.goToRgister=function(){  //验证验证码是否成功 app/slidingVerificationCode/accessTokenCode
            if (!localStorageService.get('code_token')) {
                $alert.show("请先获取验证码！");
                return false;
            }
            if ($scope.code==''||$scope.code==undefined||$scope.code==null) {
                $alert.show("验证码不能为空");
                return false;
            }
            $api.post("app/slidingVerificationCode/accessTokenCode", {mobile:$scope.telphone_no,accessToken:localStorageService.get('code_token'), code:$scope.code})
                .then(function (ret) {
                    console.log(ret);
                    if (ret.retCode == "0") {
                       // $alert.show("验证码已发送!");
                        $scope.codeStatus=false;
                    } else {
                       $alert.show("验证码验证失败，请填写正确的6位数验证码!");
                    }
                },function(err){
                    $alert.show(err);
                });
        }
    });